package activity.give;

import models.BaseModel;
import models.constants.DeletedStatus;
import play.Logger;
import play.db.jpa.JPA;
import product.merchant.ProductSpecMerchant;
import util.common.ConvertUtil;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.*;

/**
 * Created by Yangshancheng
 * on 2016/11/22.
 * Time : 下午5:30
 */
@Entity
@Table(name = "give_activity_spec_products")
public class GiveActivitySpecProduct extends BaseModel {

    /**
     * 赠送活动
     */
    @ManyToOne
    @JoinColumn(name = "give_activity_id")
    public GiveActivity giveActivity;

    /**
     * 赠送活动
     */
    @ManyToOne
    @JoinColumn(name = "product_spec_merchant_id")
    public ProductSpecMerchant productSpecMerchant;

    /**
     * 是否使用最大奖品数量
     */
    @Column(name = "use_max_count")
    public Boolean useMaxCount = false;

    /**
     * 赠品赠送数量
     */
    @Column(name = "give_num")
    public Integer giveNum = 1 ;

    /**
     * 最大数量
     */
    @Column(name = "max_count")
    public Double maxCount = 0D;

    /**
     * 已发放数量
     */
    @Column(name = "total_num")
    public Double totalNum = 0D;

    /**
     * 中奖比例
     */
    @Column(name = "proportion")
    public Double proportion;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;


    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;


    /**
     * 获取活动的商品列表
     *
     * @param giveActivityId
     * @return
     */
    public static List<GiveActivitySpecProduct> loadByGiveActivity(long giveActivityId) {
//
        return GiveActivitySpecProduct.find("giveActivity.id = ? and deleted = ?", giveActivityId, DeletedStatus.UN_DELETED).fetch();
    }

    //刪除赠品
    public static void deleteGiveSpecProducts(Integer[] delIds) {
        String str = UStringUtil.concatStr(",", delIds);
        String sql = "update give_activity_spec_products a set a.deleted = 1 where a.id in (" + str + ")";
        JPA.em().createNativeQuery(sql).executeUpdate();
    }

    //随机获得赠品
    public static GiveActivitySpecProduct getRandomProduct(Double amount, Long merchantId) {
        Logger.info("log 12000011  amount :%s  | merchantId : %s" , amount ,merchantId);
        GiveActivity giveActivity = GiveActivity.find("minAmount <= ? and maxAmount > ? and deleted = ? and merchant.id = ? order by sort asc", amount, amount, DeletedStatus.UN_DELETED, merchantId).first();
        if (giveActivity == null){
            Logger.info("log 1200005  giveActivity :%s" , "活动为空");
            return null;
        }
        List<GiveActivitySpecProduct> giveProductList = GiveActivitySpecProduct.find("deleted = ? and giveActivity.id = ? and productSpecMerchant.stock > 0 ", DeletedStatus.UN_DELETED, giveActivity.id).fetch();

        if (giveProductList == null || giveProductList.size() == 0){
            Logger.info("log 1200007  giveProductList : %s " , "赠品为空");
            return null;
        }

        //开始序列化List 为抽奖做准备
        Map<Long, GiveActivitySpecProduct> idToProduct = new HashMap<>();
        List<Long> randomList = new ArrayList<>();

        for (int i = 0; i < giveProductList.size(); i++) {
            GiveActivitySpecProduct giveProduct = giveProductList.get(i);
            if (giveProduct.useMaxCount == false || (giveProduct.useMaxCount == true && giveProduct.maxCount > 0)) {
                Long giveProductId = giveProduct.id;

                idToProduct.put(giveProductId, giveProduct);
                int proportion = ConvertUtil.toInteger(giveProduct.proportion * 100);
                for (int j = 0; j < proportion; j++) {
                    randomList.add(giveProductId);
                }
            }
        }

        //打乱排序
        Collections.shuffle(randomList);
        if (randomList == null || randomList.size() == 0) {
            Logger.info("log 1200009  randomList : %s " , "赠品randomList为空");
            return null;
        }
        // 获取1-最大值之间的一个随机数
        int luckyNumber = new Random().nextInt(randomList.size());

        long giveProductId = randomList.get(luckyNumber);

        //随机获取商品结束
        GiveActivitySpecProduct giveProduct = idToProduct.get(giveProductId);
        giveProduct.totalNum = (giveProduct.totalNum == null ? 0 : giveProduct.totalNum) + 1;

        if (giveProduct.useMaxCount)
            giveProduct.maxCount = giveProduct.maxCount == null ? 0 : (giveProduct.maxCount - 1);

        giveProduct.save();
        return  giveProduct;

    }


}
